//
//  DJOANetWorkManager.m
//  AFNetworking
//
//  Created by 陈樟权 on 2020/6/1.
//

#import "DJOANetWorkManager.h"
#import <AFNetworking/AFNetworking.h>
#import "DJOANetWorkRequest.h"
@interface DJOANetWorkManager ()
@property(nonatomic,strong)AFHTTPSessionManager *afn_manager;
@property(nonatomic,strong)AFJSONResponseSerializer *jsonResponseSerializer;
@property(nonatomic,strong)AFXMLParserResponseSerializer *xmlParserResponseSerialzier;
@end

@implementation DJOANetWorkManager

+(instancetype)manager{
    static DJOANetWorkManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]  init];
    });
    return manager;
}

-(instancetype)init{
    
    if (self = [super init]) {
        _afn_manager = [AFHTTPSessionManager manager];
        //设置默认responseSerializer
        AFHTTPResponseSerializer *serialize = [AFHTTPResponseSerializer serializer];
        serialize.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"image/jpeg", nil];
        _afn_manager.responseSerializer = serialize;
        

    }
    return self;
}

- (AFJSONResponseSerializer *)jsonResponseSerializer {
    if (!_jsonResponseSerializer) {
        _jsonResponseSerializer = [AFJSONResponseSerializer serializer];
        _jsonResponseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"image/jpeg", nil];
        _jsonResponseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)];

    }
    return _jsonResponseSerializer;
}

- (AFXMLParserResponseSerializer *)xmlParserResponseSerialzier {
    if (!_xmlParserResponseSerialzier) {
        _xmlParserResponseSerialzier = [AFXMLParserResponseSerializer serializer];
        _xmlParserResponseSerialzier.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"image/jpeg", nil];
        _xmlParserResponseSerialzier.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)];
    }
    return _xmlParserResponseSerialzier;
}

- (void)sendRequest:(DJOANetWorkRequest *)request {
    
    NSError * __autoreleasing requestSerializationError = nil;
    NSURLRequest *URLRequest = [self generateURLRequest:request error:&requestSerializationError];
    
    if (requestSerializationError) {
        if (request.enableLog) NSLog(@"requestSerializationError");
        return;
    }
    
    if (request.enableLog){
        NSLog(@"%@",request);
    }
    
    __block NSURLSessionDataTask *dataTask = nil;

    dataTask = [_afn_manager dataTaskWithRequest:URLRequest uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        request.responseObject = responseObject;
        
        NSError * __autoreleasing serializationError = nil;
        switch (request.responseSerializerType) {
            case DJOANetWorkResponseSerializerTypeHTTP:
                // Default serializer. Do nothing.
                break;
            case DJOANetWorkResponseSerializerTypeJSON:
                
            {
                request.responseObject = [self.jsonResponseSerializer responseObjectForResponse:dataTask.response data:request.responseObject error:&serializationError];
                break;
            }
            case DJOANetWorkResponseSerializerTypeXMLParser:
                request.responseObject = [self.xmlParserResponseSerialzier responseObjectForResponse:dataTask.response data:request.responseObject error:&serializationError];
                break;
        }
        

        
        if (error == nil) {
            if (request.enableLog){
                NSLog(@"success reponse from %@\n response : %@",request.baseUrl,request.responseObject);
            }
            if (request.successCompletionBlock) {
                request.successCompletionBlock(request);
            }
        } else {
            if (request.enableLog){
                NSLog(@"failure reponse from %@\n error :%@",request.baseUrl,error);
            }
            if (request.failureCompletionBlock) {
                request.failureCompletionBlock(request);
            }
        }
        
    }];
    
    
    [dataTask resume];
    
}


- (NSURLRequest *)generateURLRequest:(DJOANetWorkRequest *)request error:(NSError * _Nullable __autoreleasing *)error {
    
    AFHTTPRequestSerializer *serializer = nil;
    if (request.requestSerializerType == DJOANetWorkRequestSerializerTypeHTTP) {
        serializer = [AFHTTPRequestSerializer serializer];
    } else if (request.requestSerializerType == DJOANetWorkRequestSerializerTypeJSON) {
        serializer = [AFJSONRequestSerializer serializer];
    }
    
    serializer.timeoutInterval = request.reqeustTimeoutInterval;
    serializer.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    
    NSString *requestMethod = @"";
    switch (request.requestMethod) {
        case DJOANetWorkRequestMethodGET:
            requestMethod = @"GET";
            break;
        case DJOANetWorkRequestMethodPOST:
            requestMethod = @"POST";
            break;
        default:
            break;
    }
    
//    request = [serializer multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:error];
    NSMutableURLRequest *URLRequest = nil;
    if (request.constructingBodyBlock && request.requestMethod == DJOANetWorkRequestMethodPOST){
        URLRequest = [serializer multipartFormRequestWithMethod:requestMethod URLString:request.baseUrl parameters:request.param constructingBodyWithBlock:request.constructingBodyBlock error:error];
    }else{
        URLRequest = [serializer requestWithMethod:requestMethod URLString:request.baseUrl parameters:request.param error:error];
    }
    
    // 请求头
    URLRequest.allHTTPHeaderFields = request.header.mutableCopy;
    
    return URLRequest;
}


@end
